import { AppDataSource } from '../../data-source'
import { UserEntity } from '../../entity/user_entity'
import { Request, Response } from 'express'
import { Random } from '../../utils/random-utils'
import { responseHandler, errorHandler, paramsHandler } from '../../utils/handler-utils'


import type {
  User,
  RegisterRequestBody,
  LoginRequestBody,
  EditUserInfoRequestBody,
} from "./types";

const random = new Random()
const usersTypeormRepo = AppDataSource.getRepository(UserEntity)

class Basic {

  // 注册的处理函数
  register = async (req: Request, res: Response) => {
    try {

      // 首先声明一个注册 消息的结构体
      var registerBody = req.body as RegisterRequestBody;
      if (registerBody.name == undefined || registerBody.account == undefined || registerBody.password == undefined) {
        // 参数错误
        paramsHandler(registerBody, req, res)
        return
      }
      var user = await usersTypeormRepo.findOneBy({ account: registerBody.account })
      if (user) {
        responseHandler({
          req,
          res,
          code: 1,
          data: { msg: "账号已经存" },
          message: "注册失败",
        })
        return
      }

      let userEntity = new UserEntity()
      userEntity.userId = random.uniqueId();
      userEntity.nickName = registerBody.name;
      userEntity.account = registerBody.account;
      userEntity.password = registerBody.password;
      userEntity.email = "";
      userEntity.mobile = "";

      await usersTypeormRepo.save(userEntity)

      responseHandler({
        req,
        res,
        code: 1,
        data: userEntity,
        message: "注册成功",
      })

    } catch (error) {

      errorHandler({
        error,
        message: "注册失败",
        data: { error },
        req,
        res,
      })

    }
  }

  // 登录的处理函数
  login = async (req: Request, res: Response) => {
    // 接收表单数据(此处的userinfo含有三个属性:account,password)
    const { account, password } = req.body as LoginRequestBody;
    console.log(account)
    console.log(password)
    responseHandler({
      httpStatus: 200,
      message: "测试接口通",
      req,
      res,
    });
  }

  // 获取某用户的信息
  getUserInfo = async (req: Request, res: Response) => {

  }

  // 提交更新表单，更新某一用户的用户信息
  editUserInfo = async (req: Request, res: Response) => {

  }
}

export const basic = new Basic();
